TARGET := motor_test

CROSS_COMPILE :=
AS		= $(CROSS_COMPILE)as
LD		= $(CROSS_COMPILE)ld
CXX 	= $(CROSS_COMPILE)g++
CC		= $(CROSS_COMPILE)g++
CPP		= $(CC) -E
AR		= $(CROSS_COMPILE)ar
NM		= $(CROSS_COMPILE)nm
LDR		= $(CROSS_COMPILE)ldr
STRIP		= $(CROSS_COMPILE)strip
OBJCOPY		= $(CROSS_COMPILE)objcopy
OBJDUMP		= $(CROSS_COMPILE)objdump


#这里添加源文件目录
SRC_DIR := . can_ctrl ik leg_ctrl motor_ctrl trace
BUILD_DIR := tmp

ifeq ("$(origin O)", "command line")
  BUILD_DIR := $(O)
endif

OBJ_DIR   := $(BUILD_DIR)/obj
DEPS_DIR  := $(BUILD_DIR)/deps


BUILD_DIR := $(shell mkdir -p $(BUILD_DIR) && cd $(BUILD_DIR) && pwd)
$(if $(BUILD_DIR),, $(error failed to create output directory ))

OBJ_DIR := $(shell mkdir -p $(OBJ_DIR) && cd $(OBJ_DIR) && pwd)
$(if $(OBJ_DIR),, $(error failed to create obj directory ))

DEPS_DIR := $(shell mkdir -p $(DEPS_DIR) && cd $(DEPS_DIR) && pwd)
$(if $(DEPS_DIR),, $(error failed to create dep directory ))


#这里添加其他头文件路径
INC_DIR := -I./
INC_DIR += $(addprefix -I./, $(shell find $(SRC_DIR) -type d))
INC_DIR += $(addprefix -I./, $(shell find ./include -type d))

#这里添加编译参数
CFLAGS := $(INC_DIR) -Wall -O2
#CFLAGS := $(INC_DIR) -Wall -g
LNK_FLAGS := -L./lib
LNK_LIB := -lstdc++ -lpthread 
LNK_LIB += ./lib/libcontrolcan.so			#LNK_LIB +=-lcontrolcan

DIRS := $(shell find $(SRC_DIR) -type d)

#将每个子目录添加到搜索路径
VPATH = $(DIRS)
 
#查找src_dir下面包含子目录的所有cpp文件
SOURCES := $(foreach dir, $(DIRS), $(wildcard $(dir)/*.cpp))
SOURCES_C := $(foreach dir, $(DIRS), $(wildcard $(dir)/*.c))
OBJS    := $(addprefix $(OBJ_DIR)/,$(patsubst %.cpp,%.o,$(notdir $(SOURCES))))
OBJS_C  := $(addprefix $(OBJ_DIR)/,$(patsubst %.c,%.o,$(notdir $(SOURCES_C))))
DEPS    := $(addprefix $(DEPS_DIR)/, $(patsubst %.cpp,%.d,$(notdir $(SOURCES))))
DEPS_C  := $(addprefix $(DEPS_DIR)/, $(patsubst %.c,%.d,$(notdir $(SOURCES_C))))

#MISSING_DEPS = $(filter-out $(wildcard $(DEPS)),$(DEPS))
#MISSING_DEPS_SOURCES = $(wildcard $(patsubst %.d,%.c,$(MISSING_DEPS)))

.PHONY : clean debug

$(TARGET):$(OBJS) $(OBJS_C)
	$(CC) $^ $(LNK_FLAGS) -o $@ $(LNK_LIB)
#$(STRIP) $@

$(OBJ_DIR)/%.o :%.cpp
	$(CC) -c $(CFLAGS) -o $@ $<

$(OBJ_DIR)/%.o :%.c
	$(CC) -c $(CFLAGS) -o $@ $<

$(DEPS_DIR)/%.d:%.cpp
	@set -e; rm -rf $@;\
	$(CC) -MM $(CFLAGS) $< > $@.$$$$;\
	sed 's,\($*\)\.o[ :]*,$(OBJ_DIR)/\1.o $@ : ,g' < $@.$$$$ > $@;\
	rm -f $@.$$$$

$(DEPS_DIR)/%.d:%.c
	@set -e; rm -rf $@;\
	$(CC) -MM $(CFLAGS) $< > $@.$$$$;\
	sed 's,\($*\)\.o[ :]*,$(OBJ_DIR)/\1.o $@ : ,g' < $@.$$$$ > $@;\
	rm -f $@.$$$$

ifneq ($(MAKECMDGOALS), clean)
sinclude $(DEPS) $(DEPS_C)
endif

clean:
	rm -rf $(BUILD_DIR) $(TARGET)
debug:
	@echo $(OBJS_C)
